<template>
  <div class="task-detail-container">
    <el-card class="task-info-card">
      <div class="task-header">
        <h3 class="task-title">{{ taskDetail.planName || '未命名任务' }}</h3>
        <el-tag :type="getStatusTagType(taskDetail.taskStatus)">{{ getStatusDesc(taskDetail.taskStatus) }}</el-tag>
      </div>

      <div class="task-basic-info">
        <div class="info-row">
          <span class="info-label">任务ID：</span>
          <span class="info-value">{{ taskDetail.taskId || '-' }}</span>
          <span class="info-label ml-4">所属社区：</span>
          <span class="info-value">{{ taskDetail.communityName || '-' }}</span>
        </div>

        <div class="info-row">
          <span class="info-label">执行人：</span>
          <div class="info-value">
            <el-avatar
                :src="getAvatarUrl(taskDetail.executorId)"
                class="executor-avatar"
                size="small"
            />
            <span class="executor-name">{{ taskDetail.executorName || '未指定' }}</span>
          </div>
          <span class="info-label ml-4">创建时间：</span>
          <span class="info-value">{{ formatDateTime(taskDetail.createTime) }}</span>
        </div>

        <div class="info-row">
          <span class="info-label">计划开始时间：</span>
          <span class="info-value">{{ formatDateTime(taskDetail.plannedStartTime) }}</span>
          <span class="info-label ml-4">计划结束时间：</span>
          <span class="info-value">{{ formatDateTime(taskDetail.plannedEndTime) }}</span>
        </div>

        <div class="info-row">
          <span class="info-label">实际开始时间：</span>
          <span class="info-value">{{ formatDateTime(taskDetail.actualStartTime) || '-' }}</span>
          <span class="info-label ml-4">实际结束时间：</span>
          <span class="info-value">{{ formatDateTime(taskDetail.actualEndTime) || '-' }}</span>
        </div>

        <div class="info-row">
          <span class="info-label">任务描述：</span>
          <span class="info-value">{{ taskDetail.description || '无描述' }}</span>
        </div>
      </div>

      <div class="task-stats">
        <el-progress
            :percentage="Number(taskDetail.completionRate || 0)"
            :color="getProgressColor(Number(taskDetail.completionRate || 0))"
            :stroke-width="18"
            text-inside
        />
        <div class="stats-items">
          <div class="stats-item">
            <div class="stats-value">{{ taskDetail.totalPoints || 0 }}</div>
            <div class="stats-label">总点位</div>
          </div>
          <div class="stats-item">
            <div class="stats-value">{{ taskDetail.inspectedPoints || 0 }}</div>
            <div class="stats-label">已巡检</div>
          </div>
          <div class="stats-item">
            <div class="stats-value">{{ taskDetail.missedPoints || 0 }}</div>
            <div class="stats-label">未巡检</div>
          </div>
          <div class="stats-item">
            <div class="stats-value">{{ taskDetail.exceptionPoints || 0 }}</div>
            <div class="stats-label">异常点位</div>
          </div>
        </div>
      </div>
    </el-card>

    <div class="task-route-section">
      <el-card class="route-card">
        <div class="section-header">
          <h4>巡更路线</h4>
        </div>

        <div class="route-map" v-if="taskDetail.routeMapUrl">
          <el-image
              :src="taskDetail.routeMapUrl"
              :preview-src-list="[taskDetail.routeMapUrl]"
              fit="contain"
              class="map-image"
          >
            <template #placeholder>
              <div class="image-placeholder">加载中...</div>
            </template>
            <template #error>
              <div class="image-error">
                <el-icon><PictureFilled /></el-icon>
                <span>加载失败</span>
              </div>
            </template>
          </el-image>
        </div>

        <div class="route-points">
          <h5>路线点位</h5>
          <el-table
              :data="taskDetail.routePoints || []"
              border
              style="width: 100%;"
          >
            <el-table-column prop="sequence" label="序号" width="80" />
            <el-table-column prop="pointName" label="点位名称" width="150" />
            <el-table-column prop="pointType" label="点位类型" width="120" />
            <el-table-column label="巡检状态" width="120">
              <template #default="scope">
                <el-tag
                    :type="getPointStatusType(scope.row.status)"
                    size="small"
                >
                  {{ getPointStatusDesc(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="巡检时间" width="180" />
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button
                    size="mini"
                    type="primary"
                    @click="viewPointDetail(scope.row.pointId)"
                    v-if="scope.row.status !== 0"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>

    <div class="task-exception-section">
      <el-card class="exception-card">
        <div class="section-header">
          <h4>异常记录</h4>
          <span class="exception-count">(共 {{ taskDetail.exceptions?.length || 0 }} 条异常)</span>
        </div>

        <el-table
            :data="taskDetail.exceptions || []"
            border
            style="width: 100%;"
            v-if="taskDetail.exceptions?.length > 0"
        >
          <el-table-column prop="pointName" label="异常点位" width="150" />
          <el-table-column prop="exceptionType" label="异常类型" width="120" />
          <el-table-column prop="discoveryTime" label="发现时间" width="180" />
          <el-table-column label="异常照片" width="150">
            <template #default="scope">
              <div class="photo-preview">
                <el-image
                    v-for="(url, index) in validPhotoUrls(scope.row.photoUrls)"
                    :key="index"
                    :src="url"
                    :preview-src-list="validPhotoUrls(scope.row.photoUrls)"
                    class="preview-img"
                    fit="cover"
                    v-if="index < 2"
                >
                  <template #placeholder>
                    <div class="image-placeholder">加载中...</div>
                  </template>
                </el-image>
                <div v-if="validPhotoUrls(scope.row.photoUrls).length > 2" class="photo-count">
                  +{{ validPhotoUrls(scope.row.photoUrls).length - 2 }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="异常描述" />
          <el-table-column label="处理状态" width="120">
            <template #default="scope">
              <el-tag
                  :type="getExceptionStatusType(scope.row.processStatus)"
                  size="small"
              >
                {{ getExceptionStatusDesc(scope.row.processStatus) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <div v-else class="empty-exception">
          <el-empty description="暂无异常记录" />
        </div>
      </el-card>
    </div>

    <div class="task-actions">
      <el-button
          type="primary"
          @click="handleExport"
          icon="Download"
      >
        导出报告
      </el-button>
      <el-button
          type="info"
          @click="handlePrint"
          icon="Printer"
      >
        打印
      </el-button>
      <el-button
          type="default"
          @click="$emit('close')"
      >
        返回
      </el-button>
    </div>

    <!-- 点位详情弹窗 -->
    <el-dialog
        title="点位详情"
        v-model="pointDetailVisible"
        width="700px"
        :close-on-click-modal="false"
    >
      <point-detail :point-id="currentPointId" @close="pointDetailVisible = false" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue';
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
import {
  PictureFilled, Download, Printer,
  Location, Check, Close, WarningFilled, Clock
} from '@element-plus/icons-vue';
import { useRoute } from 'vue-router';

// 导入API
import { getTaskDetail, exportTaskReport } from '../api/PatrolTask';
import { getPointDetail } from '../api/patrolPoint';

// 导入组件
import PointDetail from './PointDetail.vue';


// 路由
const route = useRoute();

// 响应式数据
const taskDetail = ref({});
const loading = ref(false);
const pointDetailVisible = ref(false);
const currentPointId = ref(null);

// 接收父组件传递的任务ID
const props = defineProps({
  taskId: {
    type: String,
    required: true
  }
});
console.log('接收的 taskId 类型:', typeof props.taskId); // 应输出 'string'

// 加载任务详情
const loadTaskDetail = async () => {
  try {
    loading.value = true;
    // 打印参数类型，确保是 string
    console.log('调用API的taskId类型:', typeof props.taskId, '值:', props.taskId);
    let {data:data} = await getTaskDetail(props.taskId);
    console.log('获取任务详情成功:', data)
    if (data.code === 0) {
      taskDetail.value = data.data || {};
    } else {
      ElMessage.error(data.message || '获取任务详情失败');
    }
  } catch (error) {
    console.error('获取任务详情失败:', error);
    ElMessage.error('获取任务详情失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 查看点位详情
const viewPointDetail = (pointId) => {
  currentPointId.value = pointId;
  pointDetailVisible.value = true;
};

// 导出报告
const handleExport = async () => {
  try {
    loading.value = true;
    let {data:data} = await exportTaskReport(props.taskId);
    console.log('导出报告成功:', data)
    // 处理文件下载
    const blob = new Blob([data.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `巡更任务报告_${props.taskId}_${new Date().toLocaleDateString()}.xlsx`;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);

    ElMessage.success('报告导出成功');
  } catch (error) {
    console.error('导出报告失败:', error);
    ElMessage.error('导出报告失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 打印任务详情
const handlePrint = () => {
  window.print();
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-';
  const date = new Date(dateTime);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};
// 获取状态描述
const getStatusDesc = (status) => {
  const statusMap = {
    0: '未开始',
    1: '进行中',
    2: '已完成',
    3: '已暂停',
    4: '已取消',
    5: '执行失败'
  };
  return statusMap[status] || '未知状态';
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'info',      // 未开始-蓝色
    1: 'warning',   // 进行中-黄色
    2: 'success',   // 已完成-绿色
    3: 'primary',   // 已暂停-深蓝色
    4: 'danger',    // 已取消-红色
    5: 'danger'     // 执行失败-红色
  };
  return typeMap[status] || 'info';
};

// 获取点位状态描述
const getPointStatusDesc = (status) => {
  const statusMap = {
    0: '未巡检',
    1: '已巡检',
    2: '异常'
  };
  return statusMap[status] || '未知状态';
};

// 获取点位状态标签类型
const getPointStatusType = (status) => {
  const typeMap = {
    0: 'info',      // 未巡检-蓝色
    1: 'success',   // 已巡检-绿色
    2: 'danger'     // 异常-红色
  };
  return typeMap[status] || 'info';
};

// 获取异常状态描述
const getExceptionStatusDesc = (status) => {
  const statusMap = {
    0: '未处理',
    1: '已处理',
    2: '已忽略'
  };
  return statusMap[status] || '未知状态';
};

// 获取异常状态标签类型
const getExceptionStatusType = (status) => {
  const typeMap = {
    0: 'warning',   // 未处理-黄色
    1: 'success',   // 已处理-绿色
    2: 'info'       // 已忽略-蓝色
  };
  return typeMap[status] || 'info';
};

// 获取进度条颜色
const getProgressColor = (percentage) => {
  if (percentage === 100) return '#67C23A';
  if (percentage >= 80) return '#E6A23C';
  return '#F56C6C';
};

// 处理图片URL
const validPhotoUrls = (photoUrls) => {
  return (photoUrls || '')
      .split(',')
      .map(url => url.trim())
      .filter(url => url);
};

// 获取头像URL
const getAvatarUrl = (userId) => {
  // 实际项目中应该根据用户ID获取头像URL
  // 这里使用占位图
  return `https://picsum.photos/id/${userId || 1}/200/200`;
};

// 任务ID变化时重新加载数据
watch(() => props.taskId, (newVal) => {
  if (newVal) {
    loadTaskDetail();
  }
});

// 组件挂载时
onMounted(() => {
  if (props.taskId) {
    loadTaskDetail();
  }
});
</script>

<style scoped>
.task-detail-container {
  padding: 20px;
}

.task-info-card {
  margin-bottom: 20px;
}

.task-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.task-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin-right: 12px;
}

.task-basic-info {
  margin-bottom: 16px;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  flex-wrap: wrap;
}

.info-label {
  color: #606266;
  font-size: 14px;
  width: 100px;
  text-align: right;
}

.info-value {
  color: #303133;
  font-size: 14px;
  margin-left: 8px;
  flex: 1;
  max-width: calc(100% - 108px);
}

.ml-4 {
  margin-left: 16px;
}

.executor-avatar {
  margin-right: 8px;
}

.task-stats {
  margin-top: 24px;
}

.stats-items {
  display: flex;
  justify-content: space-around;
  margin-top: 16px;
}

.stats-item {
  text-align: center;
}

.stats-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.stats-label {
  font-size: 14px;
  color: #606266;
}

.task-route-section,
.task-exception-section {
  margin-bottom: 20px;
}

.route-card,
.exception-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h4 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.exception-count {
  margin-left: 8px;
  font-size: 14px;
  color: #606266;
}

.route-map {
  margin-bottom: 16px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  overflow: hidden;
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.map-image {
  max-width: 100%;
  max-height: 400px;
}

.image-placeholder,
.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
  background-color: #F5F7FA;
  color: #909399;
}

.image-error el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.route-points {
  margin-top: 16px;
}

.photo-preview {
  display: flex;
  align-items: center;
  gap: 4px;
  width: 100%;
  height: 40px;
}

.preview-img {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  cursor: pointer;
  object-fit: cover;
  border: 1px solid #eee;
}

.photo-count {
  width: 40px;
  height: 40px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #666;
  border: 1px solid #eee;
}

.empty-exception {
  padding: 30px 0;
}

.task-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin-top: 24px;
}
</style>
